package com.gitee.wsl.struct.event

import kotlin.reflect.KClass

interface EventsHandler{

    operator fun <EventType : Event> set(event: KClass<out EventType>, lambda: EventAction<EventType>)

    operator fun <EventType : Event> get(event: KClass<out EventType>): EventAction<EventType>?

}

inline fun <reified EventType : Event> EventsHandler.fireEvent(event:EventType){
    val callBlock = this[EventType::class]
    println("${EventType::class} is $callBlock")
    callBlock ?: return
    callBlock.onEvent(event)
}

inline fun <reified EventType : Event> EventsHandler.register(lambda: EventAction<EventType>)  {
    this[EventType::class] = lambda
}

open class EventsHandlerImp(
    val map: MutableMap<KClass<out Event>, EventAction<out Event>> = mutableMapOf(),
    //register: EventsHandler.() -> Unit={},
): EventsHandler {
    /*init {
        register(this)
    }*/

    override fun <EventType : Event> set(
        event: KClass<out EventType>,
        lambda: EventAction<EventType>
    ) {
        map[event]=lambda
    }

    override fun <EventType : Event> get(event: KClass<out EventType>): EventAction<EventType>? {
        return map[event] as EventAction<EventType>?
    }
}

